<template>
  <div class='home'>
    <button type='primary' @click='getPdf(`文档`)'>导出</button>
    <!-- 要转成pdf导出的html, id为resultsHuiZongTableId-->

    <div class='student-info' id='resultsHuiZongTableId'>
      <div class='duan'>
        <div class='student-info-item'>姓名：王五</div>
        <div class='student-info-item'>年龄：28</div>
        <div class='student-info-item'>高校：华水</div>
        <div class='student-info-item'>班级：6班</div>
        <div><img src='../assets/logo.png' alt='' /></div>
      </div>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import JSZip from 'jszip'
import FileSaver from 'file-saver'

export default {
  name: 'HomeView',
  data () {
    return {}
  },
  methods: {
    //   var contentWidth = canvas.width;
    //   var contentHeight = canvas.height;

    //   //一页pdf显示html页面生成的canvas高度;
    //   var pageHeight = contentWidth / 592.28 * 841.89;
    //   //未生成pdf的html页面高度
    //   var leftHeight = contentHeight;
    //   //页面偏移
    //   var position = 0;
    //   //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
    //   var imgWidth = 595.28;
    //   var imgHeight = 592.28/contentWidth * contentHeight;

    //   var pageData = canvas.toDataURL('image/jpeg', 1.0);

    //   var pdf = new jsPDF('', 'pt', 'a4');

    //   //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
    //   //当内容未超过pdf一页显示的范围，无需分页
    //   if (leftHeight < pageHeight) {
    // pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
    //   } else {
    //     while(leftHeight > 0) {
    //         pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
    //         leftHeight -= pageHeight;
    //         position -= 841.89;
    //         //避免添加空白页
    //         if(leftHeight > 0) {
    //         pdf.addPage();
    //         }
    //     }
    //   }

    // pdf.save('content.pdf');
    getPdf (title) {
      return new Promise(async (resolve) => {
        const $el = document.querySelectorAll('.duan')
        if ($el.length <= 1) {
          html2Canvas($el[0], {
            allowTaint: false,
            useCORS: true, // allowTaint、useCORS只能够出现一个
            imageTimeout: 0,
            dpi: 300, // 像素
            scale: 4 // 图片大小
          }).then(function (canvas) {
            const contentWidth = canvas.width
            const contentHeight = canvas.height
            const pageHeight = (contentWidth / 592.28) * 841.89
            let leftHeight = contentHeight
            let position = 0
            const imgWidth = 595.28
            const imgHeight = (592.28 / contentWidth) * contentHeight
            const pageData = canvas.toDataURL('image/jpeg', 1.0)
            const PDF = new JsPDF('', 'pt', 'a4')
            if (leftHeight < pageHeight) {
              PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
            } else {
              while (leftHeight > 0) {
                PDF.addImage(
                  pageData,
                  'JPEG',
                  0,
                  position,
                  imgWidth,
                  imgHeight
                )
                leftHeight -= pageHeight
                position -= 841.89
                if (leftHeight > 0) {
                  PDF.addPage()
                }
              }
            }
            // 保存 pdf 文档
            PDF.save(`${title}.pdf`)
            resolve(true)
          })
        } else {
          const zip = new JSZip()
          for (let i = 0; i < $el.length; i++) {
            html2Canvas($el[i], {
              allowTaint: false,
              useCORS: true, // allowTaint、useCORS只能够出现一个
              imageTimeout: 0,
              dpi: 300, // 像素
              scale: 4 // 图片大小
            })
              .then(async function (canvas) {
                const contentWidth = canvas.width
                const contentHeight = canvas.height
                const pageHeight = (contentWidth / 592.28) * 841.89
                let leftHeight = contentHeight
                let position = 0
                const imgWidth = 595.28
                const imgHeight = (592.28 / contentWidth) * contentHeight
                const pageData = canvas.toDataURL('image/jpeg', 1.0)
                const PDF = new JsPDF('', 'pt', 'a4')
                if (leftHeight < pageHeight) {
                  PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
                } else {
                  while (leftHeight > 0) {
                    PDF.addImage(
                      pageData,
                      'JPEG',
                      0,
                      position,
                      imgWidth,
                      imgHeight
                    )
                    leftHeight -= pageHeight
                    position -= 841.89
                    if (leftHeight > 0) {
                      PDF.addPage()
                    }
                  }
                }
                // 将pdf放到zip包
                const dataurl = PDF.output('blob')
                console.log('dateurl', dataurl)
                await zip.file(`${title}-${i}.pdf`, dataurl, { base64: true })
                console.log('1111', await zip.file(`${title}-${i}.pdf`, PDF.output('blob')))
                // 保存 pdf 文档
                // PDF.save(`${title}.pdf`);
                resolve(true)
              })
              .catch(() => {})
              .finally(() => {
                this.pdfExporting = false
                console.log(88888)
              })
          }
          const content = await zip.generateAsync({ type: 'blob' }) // 生成二进制流
          console.log('con', content)
          FileSaver.saveAs(content, '111.zip')
        }
      })
    }
  }
}
</script>

<style lang='less' scoped>
.student-info {
  width: 100%;
  .student-info-item {
    text-align: left;
  }
}
.duan {
  width: 551px;
  // height: 850px;
  padding: 40px 20px 0 20px;
  margin: auto;

  page-break-after: always;
}
.flex {
  display: flex;
  justify-content: center;
  align-content: center;
}
</style>
